<?php

namespace app\common\model;

use app\api\model\WxMessage;
use think\Db;
use \app\store\model\appointment\Order as appointmentOrder;
use \app\common\model\AppointmentOrder as OrderModel;
use app\common\model\server\User as UserModel;

/**
 * 预约模型
 * sxc 2020-8-18
 * Class Article
 * @package app\common\model
 */
class AppointmentService extends BaseModel
{
    protected $name = 'appointment_service';

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'wxapp_id',
        'create_time',
    ];

    /**
     * 开始服务
     * @param $order_id
     * @return $this|bool
     */
    function startService($order_id)
    {
        if (empty($order_id)) {
            $this->error = '订单号不能为空！';
            return false;
        }

        $order = $this->where('order_id', $order_id)->find();
        if (empty($order)) {
            $this->error = '订单不存在！';
            return false;
        }

        $AppointmentOrder = new OrderModel();
        Db::startTrans();
        $state1 = $this->where('order_id', $order_id)
            ->update([
                'is_start' => 1,
                'start_time' => time(),
            ]);

        $state2 = $AppointmentOrder->updateServerState($order_id, 3);
        if ($state1 && $state2) {
            Db::commit();
            return true;
        } else {
            $this->error = "更新失败";
            Db::rollback();
            return false;
        }
    }

    /**
     * 添加服务人员
     * @param $order_id
     * @param $service_id
     */
    public function add_service($order_id, $service_id, $price = 0, $use_time, $server_num)
    {
        $service = $this->where('order_id', $order_id)->find();
        $userModel = new UserModel;
        $service_name = $userModel->where(['user_id' => $service_id])->find();

        $serviceModel = new AppointmentService();
        $server = $serviceModel->detail($order_id);

        $appointmentInfo = appointmentOrder::get(['id' => $order_id]);

        $time_arr = explode(',',$appointmentInfo['time_id']);
        $time = Db::name('appointment_time')->where(['time_id' => ['in',$time_arr]])->column('desc');
        $time_str = '';
        foreach ($time as $key => $value){
            if($key == 0){
                $time_str .= $value;
            }else{
                $time_str .= '|'.$value;
            }

        }
        //分配服务人员，或者变更服务人员时，推送消息
        if (empty($server) || $server['service_id'] != $service_id) {
            $message = [
                'openid' => Db::name('user')->where(['user_id' => $service_id])->value('open_id'),
                'type_name' => Db::name('appointment_type')->where(['type_id' => $appointmentInfo['type_id']])->value('name'),
                'time' => date('Y-m-d', $appointmentInfo['appointment_date']) . '     ' . $time_str,
                'username' => $appointmentInfo['user_name'],
                'user_phone' => $appointmentInfo['user_phone'],
                'user_address' => $appointmentInfo['address']
            ];
            //推送预约信息
            $message_status = WxMessage::sendMessage(2, $message);

            $message_status = $message_status == false ?  '失败' :  '成功';
            //分配服务人员
            AppointmentRecord::addRecord($order_id,$message_status,2);

            //推给客户
            $day = $appointmentInfo['appointment_date'];
            $param = [
                'openid' => Db::name('user')->where(['user_id' => $appointmentInfo['user_id']])->value('open_id'),
                'name' => $service_name['real_name'],
                'mobile' => $service_name['mobile'],
                'type' => Db::name('appointment_type')->where(['type_id' => $appointmentInfo['type_id']])->value('name'),
                'time' =>  date('Y-m-d',$day)
            ];

            $message_status = WxMessage::sendMessage(3, $param);

            $message_status = $message_status == false ?  '失败' :  '成功';
            //分配服务人员
            AppointmentRecord::addRecord($order_id,$message_status,3);
            //分配服务人员
//            AppointmentRecord::addRecord($order_id,$service_name['real_name'],3);


//            $day = $appointmentInfo['appointment_date'];
//            $time = Db::name('appointment_time')->where('time_id', $appointmentInfo['time_id'])->value('name');
//            $message = [
//                'openid' => Db::name('user')->where(['user_id' => $appointmentInfo['user_id']])->value('open_id'),
//                'name' => Db::name('appointment_type')->where('type_id', $appointmentInfo['type_id'])->value('name'),
//                'time' =>  date('Y-m-d',$day) . ' ' . '' . '' . '' . $time
//            ];
//            WxMessage::sendMessage(10, $message);
        }

        if (empty($service)) {

            $this->insert([
                'order_id' => $order_id,
                'service_id' => $service_id,
                'price' => $price,
                'use_time' => $use_time,
                'server_num' => $server_num,
                'wxapp_id' => self::$wxapp_id,
                'create_time' => time(),
            ]);
        } else {
            if ($service['status'] == 1) {
                $this->error = '已完成订单不允许修改';
                return false;
            }

            $this->where('id', $service['id'])->update([
                'order_id' => $order_id,
                'service_id' => $service_id,
                'use_time' => $use_time,
                'server_num' => $server_num,
                'price' => $price,
                'update_time' => time(),
            ]);
        }

        appointmentOrder::where(['id' => $order_id])->update(['service_name' => $service_name['real_name']]);
        return true;
    }

    /**
     * 计算佣金
     * @param $order_id
     */
    function confirm_finish($order_id,$order_str_id = 0)
    {

        $info = $this->alias('s')
            ->join('appointment_order o', 'o.id = s.order_id', 'left')
            ->join('appointment_type t', 't.type_id = o.type_id', 'left')
            ->where('o.id', $order_id)
            ->field('t.*,s.service_id,s.price,s.service_price,s.id s_id,o.service_status,
        s.use_time,o.status,s.start_time,o.service_id,s.is_start,o.user_order_id')
            ->find();

        if (empty($info)) {
            $this->error = '正在安排师傅上门';
            return false;
        }

        if ($info['status'] == 2) {
            $this->error = '已服务，请不要重复确认';
            return false;
        }

        if ($info['service_status'] != 4) {
            $this->error = '服务未结束';
            return false;
        }

        $commission = 0;
        switch ($info['type']) {
            case 0:
                $commission = $info['fixation'] + $info['award'] + $info['remote_fee'];
                break;
            case 1:
                $commission = $info['price'] * $info['ratio'] / 100 + $info['award'] + $info['remote_fee'];
                break;
            case 2:
                $times = $this->where([
                    'service_id' => $info['service_id'],
                    'status' => 1,
                ])->sum("use_time");
                if ($times > $info['beyond_time'] * 60) {
                    $commission = number_format($info['time_money'] * $info['use_time'] / 60,2);
                } else {
                    $commission = 0;
                }
                break;
        }

        Db::startTrans();
        //更新服务列表状态
        $state1 = $this->where('id', $info['s_id'])->update([
            'service_price' => $commission,
            'status' => 1,
            'end_time' => time()
        ]);

        //更新订单状态
        $state2 = Db("appointment_order")->where('id', $order_id)->update([
            'status' => 2,
            'service_status' => 4,
        ]);

        $message = [
            'openid' => Db::name('user')->where(['user_id' => $info['service_id']])->value('open_id'),
            'name' => $info['name']
        ];
        //推送预约信息
        WxMessage::sendMessage(7, $message);

        $OrderModel = new OrderModel();
        $OrderModel->confirmOrderFinish($info['user_order_id']);

        if ($state1 && $state2) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            $this->error = '更新失败';
            return false;
        }
    }

    function detail($order_id, $service_id = 0)
    {
        if ($order_id > 0) return $this->where('order_id', $order_id)->find();

        if ($service_id > 0) return $this->where('service_id', $service_id)->find();

        return false;
    }
}
